import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
})

service.interceptors.request.use(config => {
    const userStore = useUserStore()
    if (userStore.token) {
        config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    return config
}, error => {
    return Promise.reject(error)
})

service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code !== 200) {
            ElMessage({
                message: res.message || 'Error',
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(new Error(res.message || 'Error'))
        }
        return res
    },
    error => {
        let message = '服务器异常'
        
        if (error.response) {
            const { status, data } = error.response
            if (status === 403) {
                message = '缺少权限使用该内容'
            } else if (data && data.message) {
                message = data.message
            } else {
                message = `请求失败 (${status})`
            }
        } else if (error.message) {
            message = error.message
        }
        
        ElMessage({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service